import { UploadOutlined } from '@ant-design/icons';
import { ProForm, ProFormText } from '@ant-design/pro-components';
import { Button, Form, message, Modal, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import type { FormInstance } from 'antd/lib/form/Form';
import type { RcFile, UploadFile, UploadProps } from 'antd/lib/upload/interface';
import { useRef, useState } from 'react';
import styles from '../style.less';
import type { createactivityItem } from '../types';

interface ParkList {
  visible: boolean;
  unVisible: () => void;
  onSubmit: (values: createactivityItem) => Promise<boolean | undefined>;
}
export default (props: ParkList) => {
  const { visible, unVisible, onSubmit: createActivity } = props;
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const formRef = useRef<FormInstance>();

  const onChange: UploadProps['onChange'] = ({ file, fileList: newFileList }) => {
    if (file.status === 'done') {
      formRef?.current?.setFieldsValue({ picture: file.response.data.url });
      message.success(`${file.name} 图片上传成功`);
    } else if (file.status === 'error') {
      message.error(`${file.name} 图片上传失败`);
    }
    setFileList(newFileList);
  };

  const onPreview = async (file: UploadFile) => {
    let src = file.url as string;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj as RcFile);
        reader.onload = () => resolve(reader.result as string);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };
  return (
    <Modal
      onCancel={unVisible}
      centered
      visible={visible}
      title="添加活动"
      width={800}
      footer={null}
    >
      <ProForm<createactivityItem>
        onFinish={(values) => createActivity(values)}
        formRef={formRef}
        className={styles.stepsaction}
      >
        <ProFormText
          width={'xl'}
          name="name"
          label="活动名称"
          placeholder="请输入"
          rules={[{ required: true, message: '请输入活动名称' }]}
        />
        <ProFormText
          width={'xl'}
          name="links"
          label="活动地址"
          placeholder="请输入"
          rules={[{ required: true, message: '请输入活动地址' }]}
        />
        <Form.Item
          name="picture"
          label="上传图片"
          // rules={[{ required: true}]}
          style={{ width: 500, height: 200 }}
          font-size="larger"
        >
          <ImgCrop
            grid
            rotate
            aspect={343 / 128}
            quality={1}
            beforeCrop={(file: File): Promise<boolean> =>
              new Promise<boolean>((resolve, rejects) => {
                const { name } = file;
                // .xlsx*表示匹配所有带有 .xlsx 的字段，$表示匹配字符串结尾位置
                const nameRegExp = new RegExp('(.jpeg|.png|.jpg)$');
                const isImage = nameRegExp.test(name);
                const isLt512K = file.size / 1024 < 512;
                if (!isImage) {
                  message.error({
                    content: '文件类型错误, 请上传一个图片文件,支持格式jp(e)g或png',
                    key: 'upload_image',
                  });
                  rejects();
                  return;
                }
                if (!isLt512K) {
                  message.error({
                    content: '文件过大，请上传一个小于512KB的文件',
                    key: 'upload_image',
                  });
                  rejects();
                  return;
                }
                resolve(true);
              })
            }
          >
            <Upload
              action="/api/file/upload/singleImage"
              listType="picture-card"
              fileList={fileList}
              onChange={onChange}
              onPreview={onPreview}
              maxCount={1}
              style={{ width: 200 }}
            >
              <Button icon={<UploadOutlined />} style={{ width: '106px', height: '106px' }}>
                <div>
                  <a>点击上传图片</a>
                </div>
                <a> (343 * 128)</a>
              </Button>
            </Upload>
          </ImgCrop>
        </Form.Item>
      </ProForm>
    </Modal>
  );
};
